package com.atguigu.split;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;
import java.util.List;

/**
 * @author yhm
 * @create 2024-04-02 15:26
 */
public class Test01_OutPut {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",8081);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 2. 读取数据源
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 8, 9, 5, 2, 3);
        DataStreamSource<Integer> streamSource = env.fromCollection(list);

        // 3. 处理数据
        // 分为两条流
        // 奇数一个流  计算和
        SingleOutputStreamOperator<Integer> streamOperator = streamSource.filter(new FilterFunction<Integer>() {
            @Override
            public boolean filter(Integer value) throws Exception {
                return value % 2 == 1;
            }
        });

        streamOperator.keyBy(new KeySelector<Integer, String>() {
            @Override
            public String getKey(Integer value) throws Exception {
                return "1";
            }
        }).sum(0)
                .map(new MapFunction<Integer, String>() {
                    @Override
                    public String map(Integer value) throws Exception {
                        return "奇数的和为:" + value;
                    }
                })
                .print();

        // 偶数一个流  计算积
        SingleOutputStreamOperator<Integer> streamOperator1 = streamSource.filter(new FilterFunction<Integer>() {
            @Override
            public boolean filter(Integer value) throws Exception {
                return value % 2 == 0;
            }
        });
        streamOperator1.keyBy(new KeySelector<Integer, String>() {
            @Override
            public String getKey(Integer value) throws Exception {
                return "2";
            }
        }).reduce(new ReduceFunction<Integer>() {
            @Override
            public Integer reduce(Integer value1, Integer value2) throws Exception {
                return value1 * value2;
            }
        }).map(new MapFunction<Integer, String>() {
            @Override
            public String map(Integer value) throws Exception {
                return "偶数的积为:" + value;
            }
        })
                .print();

        // 4. 输出

        // 5. 执行环境
        env.execute();
    }
}
